const crypto = require('crypto')
const jwt = require('jwt-simple')
const {
  loginConfig,
  tokenExp,
} = require('../../utils/constants.js')

const {
  encryptPassword
} = require("../../utils/encryptPassword.js")

const db = uniCloud.database()
async function adminlogin(event){
	let {
		mobile,
		password
	} = event
	
	let adminInfo = {
		mobile
	}
	let tokenSecret = crypto.randomBytes(16).toString('hex'),
		token = jwt.encode(adminInfo, tokenSecret);
		
	let adminInDB = await db.collection('admin').where({
	    mobile,
	    password:encryptPassword(password)
	  }).get()
	  
	if(adminInDB.data && adminInDB.data.length === 0){
		return {
		  status: -1,
		  msg: '账号或者密码错误！'
		}  
	 }
	  
	// if(adminInDB.data && adminInDB.data.length === 0){
	// 	adminResult = await db.collection('admin').add({
	// 		mobile,
	// 		password:encryptPassword(password),
	// 		tokenSecret,
	// 		exp: Date.now() + tokenExp
	// 	})
	// } else {
	// } 
	
	let adminResult = await db.collection('admin').doc(adminInDB.data[0]._id).set({
	  mobile,
	  tokenSecret,
	  exp: Date.now() + tokenExp
	})
	
	if (adminResult.id || adminResult.affectedDocs === 1) {
	  return {
	    status: 0,
	    token,
	    msg: '登录成功'
	  }
	}
		
	return {
	  status: -1,
	  msg: '微信登录失败'
	}
		
}

exports.main = adminlogin;